package com.haixee.parkdemo.auth.jwt;


import com.haixee.parkdemo.auth.jwt.alg.ECDSAJwt;
import com.haixee.parkdemo.auth.properties.WebProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.security.InvalidKeyException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author RUIFENG GUO
 * 2021/6/8 15:27
 */
@Service
@Slf4j
@AutoConfigureAfter(WebProperties.class)
public class JwtManager {

    private final Map<String, JwtOperator> jwtOperatorMap = new ConcurrentHashMap<>();

    private JwtOperator one;

    @Autowired
    private WebProperties webProperties;

    @PostConstruct
    public void init() throws InvalidKeyException {
        List<WebProperties.Jwt> jwts = webProperties.getJwt();
        if (jwts.size() == 0) {
            one = new ECDSAJwt();
            return;
        }

        for (WebProperties.Jwt jwt : jwts) {
            ECDSAJwt ecdsaJwt = new ECDSAJwt(jwt.getName(), jwt);
            jwtOperatorMap.put(jwt.getName(), ecdsaJwt);
        }

        one = jwtOperatorMap.get(jwts.get(0).getName());
    }

    public JwtOperator of(String name) {
        return jwtOperatorMap.get(name);
    }

    public JwtOperator getOne() {
        return one;
    }
}
